package com.wsx.ones.ehcache;

import com.wsx.ones.core.ehcache.BaseEhcacheManager;
import com.wsx.ones.finalstr.common.EhcacheStringUtil;
import com.wsx.ones.user.login.model.LoginUser;
import com.wsx.ones.web.model.BaseUser;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

/**
 * Created by wangshuaixin on 16/12/15.
 */
public class UserEhcacheManager extends BaseEhcacheManager{

    private static UserEhcacheManager userEhcacheManager = new UserEhcacheManager();

    private UserEhcacheManager() {
        super();
    }

    public static UserEhcacheManager getInstance() {
        return userEhcacheManager;
    }


    @Override
    public String getFileInfo() {
        return "conf/ehcache.xml";
    }

    /**
     * 获得用户缓存内容从ehcache
     * @param uid
     * @return
     */
    public BaseUser getLoginUser(String uid) {
        Cache cache = getUserCache();
        Element element = cache.get(uid);
        if (null == element) {
            return null;
        }
        return (BaseUser) element.getValue();
    }
    //获得ehcache
    private Cache getUserCache() {
        if (!getCacheManager().cacheExists(EhcacheStringUtil.USER_CACHE)) {
            getCacheManager().addCache(EhcacheStringUtil.USER_CACHE);
        }
        return getCacheManager().getCache(EhcacheStringUtil.USER_CACHE);
    }


    /**
     * 设置用户缓存在ehcache
     * @param baseUser
     * @return
     */
    public BaseUser setBaseUser(BaseUser baseUser) {
        Element element = new Element(baseUser.getUid(), baseUser);
        if (!getCacheManager().cacheExists(EhcacheStringUtil.USER_CACHE)) {
            getCacheManager().addCache(EhcacheStringUtil.USER_CACHE);
        }
        getCacheManager().getCache(EhcacheStringUtil.USER_CACHE).put(element);
        return baseUser;
    }

}
